<template>
  <div class="sidebar">
    <div class="sidebar__toggle" @click="toggle">
      <div :class="icon">
        <i class="iconfont icon-collapsed"></i>
      </div>
    </div>
    <xdh-menu-toggle
      v-if="menus"
      class="sidebar__nav"
      :data="menus"
      :props="props"
      :router="true"
      :default-active="active"
      @select="handleSelect"
      :unique-opened="true"
      :collapse="collapsed"></xdh-menu-toggle>
  </div>
</template>


<script>
  import XdhMenuToggle from '@/widgets/xdh-menu-toggle'

  const navData = require('../nav.json')

  const findItem = function (array, path) {
    let result = null
    for (let i = 0, len = array.length; i < len; i++) {
      let item = array[i]
      if (item.path === path) {
        result = item
        break
      } else if (item.children && item.children.length > 0) {
        result = findItem(item.children, path)
        if (result) break
      }
    }
    return result
  }
  export default {
    components: {
      XdhMenuToggle
    },
    props: {
      width: {
        type: String,
        default: '250px'
      }
    },
    data() {
      return {
        collapsed: false,
        props: {
          id: 'path',
          text: 'text',
          icon: 'icon',
          children: 'children',
          group: 'group',
          route: 'route'
        },
        menus: [],
        active: this.$route.path
      }
    },
    watch: {
      collapsed(val) {
        this.$emit('update:width', val ? '65px' : '250px')
      },
      '$route.path'(path) {
        this.menus = this.getMenuData(path)
        this.active = path
      }
    },
    computed: {
      icon() {
        return this.collapsed ? 'toggle--collapsed' : 'toggle--expand'
      }
    },
    methods: {
      toggle() {
        this.collapsed = !this.collapsed
      },
      handleSelect(index) {
        const item = findItem(this.menus || [], index)
        if (item) {
          switch (item.type) {
            case 'window':
              const regex = /^(http|https):\/\//
              if (regex.test(item.path)) {
                window.open(item.path)
              } else {
                window.open(`${window.location.pathname}#${item.path}`)
              }
              break
            case 'iframe':
              this.$router.push(`/demo/frame/${encodeURIComponent(item.path)}`)
              break
            default:
              this.$router.push(item.path)
              break
          }
        }
      },
      getMenuData(path) {
        let root = path.split('/')[1]
        let result = []
        Object.keys(navData).forEach(item => {
          if (item === root) {
            result = navData[item]
          }
        })
        return result
      }
    },
    created() {
      this.menus = this.getMenuData(this.$route.path)
      this.active = this.$route.path
    }
  }
</script>
